/*
 * opencv.cpp
 *
 *  Created on: 7 mai 2012
 *      Author: clement
 */

#include "opencv.hpp"

Opencv::Opencv()
{
	Nom = "default";
	init(Nom);
}

Opencv::Opencv(string _n)
{
	Nom = _n;
	init(Nom);
}

void Opencv::init(string _window)
{
	string tmp;
	capture = cvCreateCameraCapture(CV_CAP_ANY);

	if (!capture)
	{
		cout << "Ouverture du flux vidéo impossible !" << endl;
	}
	else
	{
		Nom = _window;
		cvNamedWindow(Nom.c_str());
		tmp = Nom +" HSV";
		cvNamedWindow(tmp.c_str());
		tmp = Nom + " Masque";
		cvNamedWindow(tmp.c_str());
		noyau = cvCreateStructuringElementEx(5, 5, 2, 2, CV_SHAPE_ELLIPSE);
		cvSetMouseCallback(Nom.c_str(), static_mouse, this);
	}
}

void Opencv::AfficheCouleur()
{
	cvShowImage(Nom.c_str(), image);
}
void Opencv::AfficheHSV()
{
	string tmp;
	tmp = Nom + " HSV";
	cvShowImage(tmp.c_str(), hsv);
}
void Opencv::AfficheMasque()
{
	string tmp;
	tmp = Nom + " Masque";
	cvShowImage(tmp.c_str(), masque);
}

void Opencv::AfficheAll()
{
	AfficheCouleur();
	AfficheHSV();
	AfficheMasque();
}

void Opencv::PlaceCouleur(int _x, int _y)
{
	cvMoveWindow(Nom.c_str(), _x, _y);
}
void Opencv::PlaceHSV(int _x, int _y)
{
	string tmp;
	tmp = Nom + " HSV";
	cvMoveWindow(tmp.c_str(), _x, _y);
}
void Opencv::PlaceMasque(int _x, int _y)
{
	string tmp;
	tmp = Nom + " Masque";
	cvMoveWindow(tmp.c_str(), _x, _y);
}
void Opencv::Place(int _x, int _y)
{
	PlaceCouleur(_x, _y);
	PlaceHSV(_x, _y);
	PlaceMasque(_x, _y);
}

void Opencv::Frame()
{
	image = cvQueryFrame(capture);
	hsv = cvCloneImage(image);
	cvCvtColor(image, hsv, CV_BGR2HSV);

	masque = cvCreateImage(cvGetSize(image), image->depth, 1);
}

void Opencv::MasqueForme()
{
	cvInRangeS(hsv, cvScalar(h - RANGE -1, s - RANGE, 0), cvScalar(h + RANGE - 1, s + RANGE, 255), masque);

	cvDilate(masque, masque, noyau, 1);
	cvErode(masque, masque, noyau, 1);
}

void Opencv::getMouseColor(int event, int x, int y, int flags, void *param = NULL)
{
	CvScalar pixel;
	IplImage *tmphsv;
	if(event == CV_EVENT_LBUTTONUP)
	{
		// Get the hsv image
		tmphsv = cvCloneImage(image);
		cvCvtColor(image, tmphsv, CV_BGR2HSV);

		// Get the selected pixel
		pixel = cvGet2D(tmphsv, y, x);

		// Change the value of the tracked color with the color of the selected pixel
		h = (int)pixel.val[0];
		s = (int)pixel.val[1];
		v = (int)pixel.val[2];

		// Release the memory of the hsv image
		cvReleaseImage(&tmphsv);
	}
}

Opencv::~Opencv()
{
	cvReleaseImage(&hsv);
	cvReleaseImage(&masque);
	cvReleaseStructuringElement(&noyau);

	cvReleaseCapture(&capture);
	cvDestroyWindow("GeckoGeek Window");
}










